package com.hfy.pcberpbackend.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hfy.pcberpbackend.entity.Customer;
import com.hfy.pcberpbackend.mapper.CustomerMapper;
import com.hfy.pcberpbackend.service.CustomerService;
import com.hfy.pcberpbackend.dto.CustomerQueryDTO;
import com.hfy.pcberpbackend.common.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

/**
 * 客户Service实现类
 */
@Slf4j
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    
    @Override
    public PageResult<Customer> getCustomerPage(CustomerQueryDTO query) {
        log.info("分页查询客户列表，查询条件：{}", query);
        
        Page<Customer> page = new Page<>(query.getPage(), query.getSize());
        IPage<Customer> result = baseMapper.selectCustomerPage(page, query);
        
        return PageResult.of(result.getRecords(), result.getTotal(), 
                           result.getCurrent(), result.getSize());
    }
    
    @Override
    public Customer getCustomerById(Long id) {
        log.info("根据ID获取客户详情，ID：{}", id);
        
        Customer customer = getById(id);
        if (customer == null) {
            throw new RuntimeException("客户不存在");
        }
        return customer;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createCustomer(Customer customer) {
        log.info("新增客户：{}", customer);
        
        // 检查客户代码是否存在
        if (isCustomerCodeExists(customer.getCustomerCode(), null)) {
            throw new RuntimeException("客户代码已存在");
        }
        
        // 设置默认状态
        if (StrUtil.isBlank(customer.getStatus())) {
            customer.setStatus("active");
        }
        
        save(customer);
        return customer.getId();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCustomer(Long id, Customer customer) {
        log.info("更新客户信息，ID：{}，数据：{}", id, customer);
        
        // 检查客户是否存在
        Customer existingCustomer = getCustomerById(id);
        
        // 检查客户代码是否重复（排除自己）
        if (StrUtil.isNotBlank(customer.getCustomerCode()) && 
            !customer.getCustomerCode().equals(existingCustomer.getCustomerCode()) &&
            isCustomerCodeExists(customer.getCustomerCode(), id)) {
            throw new RuntimeException("客户代码已存在");
        }
        
        // 更新数据
        customer.setId(id);
        updateById(customer);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCustomer(Long id) {
        log.info("删除客户，ID：{}", id);
        
        // 检查客户是否存在
        getCustomerById(id);
        
        // 逻辑删除
        removeById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteCustomers(List<Long> ids) {
        log.info("批量删除客户，IDs：{}", ids);
        
        if (ids == null || ids.isEmpty()) {
            throw new RuntimeException("删除的ID列表不能为空");
        }
        
        // 批量逻辑删除
        removeByIds(ids);
    }
    
    @Override
    public boolean isCustomerCodeExists(String customerCode, Long excludeId) {
        if (StrUtil.isBlank(customerCode)) {
            return false;
        }
        
        int count = baseMapper.countByCustomerCode(customerCode, excludeId);
        return count > 0;
    }
    
    @Override
    public List<Customer> searchCustomers(String keyword, Integer size) {
        log.info("模糊搜索客户，关键词：{}，数量限制：{}", keyword, size);
        
        if (StrUtil.isBlank(keyword)) {
            return new ArrayList<>();
        }
        
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(qw -> qw
                .like(Customer::getCustomerCode, keyword)
                .or()
                .like(Customer::getCustomerName, keyword)
                .or()
                .like(Customer::getCompanyName, keyword)
        );
        wrapper.eq(Customer::getStatus, "active");
        wrapper.orderByDesc(Customer::getUpdatedAt);
        
        if (size != null && size > 0) {
            wrapper.last("LIMIT " + size);
        }
        
        return list(wrapper);
    }
    
    @Override
    public Customer getCustomerByCode(String customerCode) {
        log.info("根据客户代码获取客户详情，客户代码：{}", customerCode);
        
        if (StrUtil.isBlank(customerCode)) {
            throw new RuntimeException("客户代码不能为空");
        }
        
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Customer::getCustomerCode, customerCode);
        wrapper.eq(Customer::getStatus, "active");
        
        Customer customer = getOne(wrapper);
        if (customer == null) {
            throw new RuntimeException("客户不存在或已停用");
        }
        
        return customer;
    }
} 